<?php

namespace app\tools;

use Yii;
use app\tools\Curl;
use app\models\Area;

class Map {
  //根据地址获取经纬度
  public static function getLngLat($address) {
    $key = Yii::$app->params['map_key'];
		$url = "https://restapi.amap.com/v3/geocode/geo?key=".$key."&address=".$address;
		$res = Curl::curl_get($url);
		$res = json_decode($res);
    $location = $res->geocodes[0]->location;
    $location_arr = explode(',', $location);
		return $location_arr;
  }

  //根据经纬度获取地址
  public static function getArea($location) {
    $key = Yii::$app->params['map_key'];
		$url = "https://restapi.amap.com/v3/geocode/regeo?key=".$key."&location=".$location;
		$res = Curl::curl_get($url);
		$res = json_decode($res);
		return $res->regeocode->addressComponent;
  }

  //根据经纬度计算距离
  public static function getDistance($lat1, $lon1, $lat2, $lon2) {
    // 地球半径（单位：米）
    $earthRadius = 6371;
    // 将角度转换为弧度
    $lat1 = deg2rad($lat1);
    $lon1 = deg2rad($lon1);
    $lat2 = deg2rad($lat2);
    $lon2 = deg2rad($lon2);
    // 计算经纬度差值
    $latDiff = $lat2 - $lat1;
    $lonDiff = $lon2 - $lon1;
    // 计算Haversine公式
    $a = pow(sin($latDiff / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($lonDiff / 2), 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $distance = $earthRadius * $c;
    return number_format($distance, 2) . 'km';
  }
}
